package com.zzxz.practicaltrainingsys.service;

import com.alibaba.fastjson.JSON;
import com.zzxz.practicaltrainingsys.config.OllamaConfig;
import com.zzxz.practicaltrainingsys.dto.OllamaRequest;
import com.zzxz.practicaltrainingsys.dto.OllamaResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OllamaService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OllamaConfig ollamaConfig;

    public String generateResponse(String prompt) {
        try {
            // 构建请求
            OllamaRequest request = new OllamaRequest(ollamaConfig.getModel(), prompt);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建请求实体
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(request), headers);

            // 发送请求
            String url = ollamaConfig.getBaseUrl() + "/api/generate";
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                OllamaResponse ollamaResponse = JSON.parseObject(response.getBody(), OllamaResponse.class);
                return ollamaResponse.getResponse();
            } else {
                return "抱歉，AI服务暂时不可用，请稍后再试。";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "抱歉，处理您的请求时出现了错误：" + e.getMessage();
        }
    }
}
